#!/bin/bash

FRAMEWORK_NAME=wax
FRAMEWORK_VERSION=A
FRAMEWORK_CURRENT_VERSION=0.9
FRAMEWORK_COMPATIBILITY_VERSION=0.9
BUILD_TYPE=Release

# This is the full name of the framework we'll  build
FRAMEWORK_DIR=$FRAMEWORK_NAME.framework

# Clean any existing framework that might be there already
echo "Framework: Cleaning framework..."
[ -d "$FRAMEWORK_DIR" ] && \
  rm -rf "$FRAMEWORK_DIR"

# Build the canonical Framework bundle directory structure
echo "Framework: Setting up directories..."
mkdir -p $FRAMEWORK_DIR
mkdir -p $FRAMEWORK_DIR/Versions
mkdir -p $FRAMEWORK_DIR/Versions/$FRAMEWORK_VERSION
mkdir -p $FRAMEWORK_DIR/Versions/$FRAMEWORK_VERSION/Resources
mkdir -p $FRAMEWORK_DIR/Versions/$FRAMEWORK_VERSION/Headers

echo "Framework: Creating symlinks..."
ln -s $FRAMEWORK_VERSION $FRAMEWORK_DIR/Versions/Current
ln -s Versions/Current/Headers $FRAMEWORK_DIR/Headers
ln -s Versions/Current/Resources $FRAMEWORK_DIR/Resources
ln -s Versions/Current/$FRAMEWORK_NAME $FRAMEWORK_DIR/$FRAMEWORK_NAME

# Check that this is what your static libraries are called
FRAMEWORK_INPUT_ARM_FILES="build/$BUILD_TYPE-iphoneos/lib$FRAMEWORK_NAME.a"
FRAMEWORK_INPUT_I386_FILES="build/$BUILD_TYPE-iphonesimulator/lib$FRAMEWORK_NAME.a"

# The trick for creating a fully usable library is
# to use lipo to glue the different library
# versions together into one file. When an
# application is linked to this library, the
# linker will extract the appropriate platform
# version and use that.
# The library file is given the same name as the
# framework with no .a extension.

echo "Framework: Creating library..."

lipo \
  "$FRAMEWORK_INPUT_ARM_FILES" \
  -create \
  -arch i386 "$FRAMEWORK_INPUT_I386_FILES" \
  -o "$FRAMEWORK_DIR/Versions/Current/$FRAMEWORK_NAME"

# Now copy the final assets over: your library
# header files and the plist file
echo "Framework: Copying assets into current version..."

cp wax/lib/wax.h $FRAMEWORK_DIR/Headers/
cp wax/lib/lua/lua.h $FRAMEWORK_DIR/Headers/
cp wax/lib/lua/luaconf.h $FRAMEWORK_DIR/Headers/
cp wax/lib/extensions/HTTP/wax_http.h $FRAMEWORK_DIR/Headers/
cp wax/lib/extensions/json/wax_json.h $FRAMEWORK_DIR/Headers/
cp wax/lib/extensions/xml/wax_xml.h $FRAMEWORK_DIR/Headers/
cp wax/lib/extensions/filesystem/wax_filesystem.h $FRAMEWORK_DIR/Headers/

cp Framework.plist $FRAMEWORK_DIR/Resources/Info.plist
cp wax/lib/build-scripts/copy-scripts.sh $FRAMEWORK_DIR/Resources/
cp wax/lib/project.rake $FRAMEWORK_DIR/Resources/
cp -RL wax/bin $FRAMEWORK_DIR/Resources/


# Copy into wax's framework dir
WAX_FRAMEWORK_DIR="../../framework"
rm -rf "$WAX_FRAMEWORK_DIR/wax.framework"
mv "wax.framework" "$WAX_FRAMEWORK_DIR"
